<?php
if(!defined('IN_TTAE')) exit('Access Denied'); 

class api_im {
		public $is_open = false;
		function add($member,$bat = false){
			global $_G;
			if(!$this->is_open) return false;
			if(!class_exists('OpenimUsersAddRequest'))include_once	(ROOT_PATH.'top/im/OpenimUsersAddRequest.php');	
			
			if(!$bat){
				$user = $this->cover_user($member);
			}else{
				$user = array();
				foreach($member as $k=>$v){
					$user[] = $this->cover_user($v);
				}
			}

			$req = new OpenimUsersAddRequest;
			$req->setUserinfos(json_encode($user));
			$resp = $_G['TOP']->execute($req);
						
			top_check_error($resp,$bat);

			if($bat) return true;
			return ($this->uid_succ->string[0]);
			 
		}
		
private		function cover_user($member){
			if(isset($member['icon_url']) && isset($member['userid'])) return $member;
			$user = array();
			$user['nick'] 		= $member['username'];
			$user['icon_url'] 	= $member['picurl'];
			$user['email'] 		= $member['email'];
			$user['mobile'] 	= $member['phone'];			
			$user['userid'] 	= $member['uid'];
			$user['password'] = substr(md5($member['uid'].$member['username']),0,10);
			return $user;
		}
		
		function get_password($user){
				global $_G;
				if(!$this->is_open) return false;
				if(!$_G['uid']) return false;
				if(!$user){
					$user['uid'] = $_G['uid'];
					$user['username'] = $_G['username'];
				}
				return substr(md5($member['uid'].$member['username']),0,10);				
		}
		
		function get_user($uid){
			global $_G;
			if(!$this->is_open) return false;
			if(!$uid) $uid = $_G['uid'];
			if(!class_exists('OpenimUsersGetRequest'))include_once	(ROOT_PATH.'top/im/OpenimUsersGetRequest.php');	
			$req = new OpenimUsersGetRequest;
			$req->setUserids($uid);
			$resp = $_G['TOP']->execute($req);
			top_check_error($resp,true);
			$user = (array)$resp->userinfos->userinfos[0];
			return $user;				
		}
		
		
		//将站内用户全部同步到云账号,一个站只执行一次就行,在第一次要使用IM时执行.其它时候都会自动同步的
		function bat_add_user(){
			global $_G;
			if(!$this->is_open) return false;

			if(!class_exists('OpenimUsersAddRequest'))include_once	(ROOT_PATH.'top/im/OpenimUsersAddRequest.php');	
			$rs = DB::fetch_all("SELECT username,picurl,email,phone,uid FROM ".DB::table('member')." ORDER BY uid DESC");
			$arr = array_chunk($rs,50);
			
			foreach($arr as $k=>$v){
				$this->add($v,true);
			}

			return true;
		}
		
		
		
}

?>